/**
 * 
 */
package serialisierung;

import fpt.com.Product;

import java.io.*;

public class BinaryStrategy implements
		fpt.com.SerializableStrategy {
	
	private FileInputStream fi = null;
	private ObjectInputStream oi;
	
	private FileOutputStream fo = null;
	private ObjectOutputStream oo;

	@Override
	public Product readObject() throws IOException {
		
		if(fi == null){
			
			fi = new FileInputStream("products.ser");
			oi = new ObjectInputStream(fi);
		}
		
		try{
			return (Product) oi.readObject();
		} catch (ClassNotFoundException e){
			e.printStackTrace();
			return null;
		}

	}

	@Override
	public void writeObject(Product p) throws IOException {
		
		if (fo == null){
			fo = new FileOutputStream("products.ser");
			oo = new ObjectOutputStream(fo);
		}
			oo.writeObject(p);
			oo.flush();
		
	}

	@Override
	public void close() throws IOException {
		
		// Schließe ObjectInputStream
		if (oi != null) {
			oi.close();
		}

		// Schließe FileOutputStream
		if (fo != null) {
			fo.close();
			fo = null;
		}

		// Schließe ObjectOutputStream
		if (oo != null) {
			oo.close();
		}

		// Schließe FileInputStream
		if (fi != null) {
			fi.close();
			fi = null;
		}

	}

}
